{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 多指针操作\n",
    "\n",
    "\n",
    "用于链表反转、链表有环、最大回文数等问题\n",
    "\n",
    "\n",
    "问题：判断链表是否有环\n",
    "方法：快指针和慢指针\n",
    "\n",
    "<img src=\"./linked-list-circle.png\" style=\"margin-left:0px; width:800px;\"/>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "class Node:\n",
    "    def __init__(self, data):\n",
    "        self.data = data\n",
    "        self.next = None"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "def list_have_loop(link_list):\n",
    "    \"\"\" 默认返回没有环路 \"\"\"\n",
    "    plow = pfast = link_list\n",
    "    # pfast走的快，判断它是否结束\n",
    "    while pfast and pfast.next:\n",
    "        plow = plow.next\n",
    "        pfast = pfast.next.next\n",
    "        if plow == pfast:\n",
    "            return True\n",
    "    return False"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "True"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "root, p1, p2, p3, p4, p5 = (\n",
    "    Node(0), Node(1), Node(2), Node(3), Node(4), Node(5))\n",
    "\n",
    "# p5的next是p2，构成环路\n",
    "root.next, p1.next, p2.next, p3.next, p4.next, p5.next = (\n",
    "    p1, p2, p3, p4, p5, p2)\n",
    "\n",
    "list_have_loop(root)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
